package com.bins.cloud.gateway.filter;

import com.bins.cloud.gateway.entity.IpRateEntity;
import com.bins.cloud.gateway.limiter.CustomRedisRateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * IP限流过滤器
 */
@Slf4j
@Component
public class IpRateGlobalFilter implements Ordered, GlobalFilter {

    @Autowired
    private CustomRedisRateLimiter customRedisRateLimiter;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取到调用客户端的IP地址
        String ip = exchange.getRequest().getRemoteAddress().getHostName();
        log.info("ip:{}", ip);
        //从数据库中获取到该IP地址对应的限流参数
        IpRateEntity ipRate = new IpRateEntity();
        ipRate.setReplenishRate(1);
        ipRate.setBurstCapacity(1);

        //如果允许同行，没有超过该ip的流量限制
        if (customRedisRateLimiter.isAllowed("ip:" + ip + ":",
                ipRate.getReplenishRate(),
                ipRate.getBurstCapacity())) {
            return chain.filter(exchange);
        } else {
            exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
            return exchange.getResponse().setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}